package com.apkcore.core.util

import java.math.BigInteger
import java.nio.charset.Charset

object HexUtil {

    fun toAddress(macAddress: String): String {
        if (macAddress.contains(":")|| macAddress.length % 2 != 0) {
            return macAddress
        }
        return macAddress.chunked(2).joinToString(":")
    }

    fun reverseText(text: String, chunkSize: Int = 2): String {
        var address = text
        if (text.contains(":")) {
            address = text.replace(":", "")
        }
        if (address.length % 2 != 0) {
            return address
        }
        val reversedChunks = address.chunked(chunkSize).reversed()
        return reversedChunks.joinToString("")
    }

    fun bytes2Hex(byteArray: ByteArray?): String {
        if (byteArray == null) {
            return ""
        }
        val bigInt = BigInteger(1, byteArray)
        return String.format("%0" + (byteArray.size shl 1) + "X", bigInt).trim()
    }

    fun bytes2Text(byteArray: ByteArray?, charset: Charset = Charsets.UTF_8): String {
        if (byteArray == null) {
            return ""
        }
        return String(byteArray, charset)
    }

    fun hex2Bytes(hex: String): ByteArray {
        return hex.chunked(2) { it.toString().toInt(16).toByte() }.toByteArray()
    }
}